import { Injectable } from '@angular/core';
import { Headers, Http } from '@angular/http';
import 'rxjs/add/operator/toPromise';
import { Hero } from './Hero';




@Injectable()
export class HeroServcie {

    private heroesUri = 'api/heroes';

    private headers = new Headers({ 'Content-type': 'application/json' });

    constructor(
        private http: Http

    ) { };

    //返回预定义的数组数据
    //使用承诺模式进行数据请求，此处立即返回结果
    getHeros(): Promise<Hero[]> {
        return this.http.get(this.heroesUri)
            .toPromise()
            .then(response => response.json().data as Hero[])
            .catch(this.handlerError);
    }



    //获取指定id的hero
    getHero(id: number): Promise<Hero> {
        //注意这里的``而不是'',这是有区别的，并且错误的使用会导致参数ID无法解析
        const url = `${this.heroesUri}/${id}`;
        return this.http.get(url)
            .toPromise()
            .then(response => response.json().data as Hero)
            .catch(this.handlerError);
    }

    update(hero: Hero): Promise<Hero> {
        const url = `${this.heroesUri}/${hero.id}`;
        return this.http
            .put(url, JSON.stringify(hero), { headers: this.headers })
            .toPromise()
            .then(() => hero)
            .catch(this.handlerError);
    }

    create(name:string):Promise<Hero>{
        return this.http
            .post(this.heroesUri,JSON.stringify({name:name}),{headers:this.headers})
            .toPromise()
            .then(res => res.json().data)
            .catch(this.handlerError);
    }

    delete(id:number):Promise<void> {
        const url = `${this.heroesUri}/${id}`;
        return this.http.delete(url,{headers:this.headers})
            .toPromise()
            .then(() => null)
            .catch(this.handlerError);
    }

    private handlerError(error: any): Promise<any> {
        console.error('an error  occurred', error);
        return Promise.reject(error.message || error);
    }

}